package cc.taofoo.NIO;

import cn.hutool.core.date.DateTime;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Client {
    static SocketChannel socketChannel;

    public static void main(String[] args) throws IOException, InterruptedException {
        test();
    }



    public static void test() throws IOException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 3; i++) {
            executorService.submit(new Sender());
        }
        executorService.shutdown();
    }


}

class Sender implements Runnable {
    SocketChannel socketChannel;

    @Override
    public void run() {
        try {
            socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress("localhost", 8080));

            write("df");
            Thread.sleep(4000);
            write("df");
            socketChannel.close();
        } catch (Exception e) {

        }
    }

    public void write(String msg) throws IOException {
        String newData = msg + "  " + DateTime.now().toString() + "  ";
        ByteBuffer buf = ByteBuffer.allocate(48);
        buf.clear();
        buf.put(newData.getBytes());
        buf.flip();
        while (buf.hasRemaining()) {
            socketChannel.write(buf);
        }

    }




}